import os.path

from flask import Flask, request, jsonify
import flask
import jwt
import speech_recognition as sr
from datetime import datetime, timedelta
from BenToQing.analysis import sentiment_classify
from YuToBen.调用prompt的GPT接口 import prompt_gpt3

# jwt token相关参数
salt = "VRTreat"
exp = datetime.now() + timedelta(days=7)
cur_path = os.getcwd()

app = Flask(__name__)


# jwt过滤器，校验token
@app.before_request
def jwt_check():
    if flask.request.path == '/login':
        return None
    user_token = flask.request.headers['token']
    user = jwt.decode(user_token, salt, algorithms=["HS256"])
    if (user["username"] == "admin" and user["password"] == "123456"):
        return None
    return "用户未登录"


@app.route('/hello')
def hello_world():  # put application's code here
    return 'Hello World!'


# 将传输过来的音频数据进行语音转文本
@app.route("/answer", methods=["POST"])
def question_answer():
    try:
        # 检查是否有上传的文件
        if "audio" not in request.files:
            return jsonify({"error": "No audio file uploaded"})

        audio_file = request.files["audio"]

        audio_file.save(audio_file.filename+"2")

        # 创建语音识别器对象
        recognizer = sr.Recognizer()

        # 使用语音识别器识别上传的音频文件
        with sr.AudioFile(audio_file.filename+"2") as source:
            audio_data = recognizer.record(source)
            try:
                text = recognizer.recognize_google(audio_data,language='zh-CN')
                os.remove(audio_file.filename+"2")
                return jsonify(text, prompt_gpt3(text))
            except sr.UnknownValueError:
                return jsonify({"error": "Unable to transcribe audio"})
            except sr.RequestError as e:
                return jsonify({"error": str(e)})
    except Exception as e:
        return jsonify({"error": str(e)})


@app.route("/analysis", methods=[ 'POST'])
def analysis():
    number = request.form['number']
    text = ""
    try:
        # 检查是否有上传的文件
        if "audio" not in request.files:
            return jsonify({"error": "No audio file uploaded"})

        audio_file = request.files["audio"]
        audio_file.save(audio_file.filename+"1")
        # 创建语音识别器对象
        recognizer = sr.Recognizer()

        # 使用语音识别器识别上传的音频文件
        with sr.AudioFile(audio_file.filename+"1") as source:
            audio_data = recognizer.record(source)
            try:
                text = recognizer.recognize_google(audio_data,language="zh-CN")
                rank = str(sentiment_classify(text))
                with open("rank.txt","a") as file:
                    file.write(str(rank)+"\n")
                    os.remove(audio_file.filename+"1")
                return jsonify(text,rank)
            except sr.UnknownValueError:
                return jsonify({"error": "Unable to transcribe audio"})
            except sr.RequestError as e:
                return jsonify({"error": str(e)})
    except Exception as e:
        return jsonify({"error": str(e)})

@app.route("/analysis",methods=['GET'])
def get_analysis():
    analysis_result=[]
    with open("rank.txt","r") as file:
        for line in  file:
            analysis_result.append(float(line.strip()))
    return  analysis_result

@app.route("/test", methods=['POST', 'GET'])
def test(txt):
    return sentiment_classify(txt)


# 登录接口，放回接口权限token
@app.route("/login", methods=['POST'])
def login():
    user = flask.request.get_json()
    if (user['username'] == "admin" and user['password'] == "123456"):
        payload = {
            'exp': datetime.now() + timedelta(days=7),
            'username': user["username"],
            'password': user["password"]
        }
        return jwt.encode(payload, salt, algorithm="HS256")
    return "用户名或密码错误"


if __name__ == "__main__":
    app.run(host="0.0.0.0", port=6868)
